<template>
  <div class="container product-container">
    <Headbar/>
    <Hungbar ref="Hungbar"/>
    <HeadMenu ref="HeadMenu" :info="info"/>
    <NavList v-if="info && goodsClassify" :factoryId="info.id" :classify="goodsClassify"/>
    <div class="product-detail-wrap over">
      <div class="pd-inner-content yh-layout-box">
        <BreadCrumb :id="id" />
        <div class="product-detail-pub">
          <div class="product-detail-show fl">
            <ProductZoomer :images="content.images" ></ProductZoomer>
<!--            <div class="pd-image">-->
<!--              <img :src="URL.PIC+contentFirstImg" class="product-scale-images" :alt="content.title+','+content.factoryName">-->
<!--            </div>-->
<!--            <div class="pd-detail-scroll">-->
<!--                  <span :class="active == i?'per-detail-pic active' : 'per-detail-pic'"-->
<!--                        v-for="(item,i) in content.images" :key="i" @mouseenter="changeImage(item.imageURL, i)">-->
<!--                    <img :src="URL.PIC+item.imageURL" height="50px" width="50px"/>-->
<!--                  </span>-->

<!--            </div>-->
            <div class="pd-operate-item">
              <span class="pd-share-btn cursor" @click="shareProduct()">
                <img src="../../assets/images/product/detail/detail_02.png">
                分享
              </span>
              <span class="pd-collect-btn" @click="addFavorites">
                <img src="../../assets/images/product/detail/detail_03.png">
                收藏商品（{{favoritesCount}}）
              </span>
            </div>
              <!-- <div :class="activeShare?'':'share-style'">
                <vshare :vshareConfig="vshareConfig"/>
              </div> -->
          </div>

         <div class="product-detail-msg fl">
            <div class="product-title">
              {{content.title}}
            </div>
            <div class="purchase-pd-ins">
              <div class="purchase-price">
                <div class="purchase-item">
                  <span class="purchase-left-con">采购价</span>
                  <span class="purchase-right-con price-num">￥{{salepPrice}}</span>
                  <!-- <span class="purchase-right-con price-num filterPrice" v-html="filterPrice(salepPrice)"></span> -->

                </div>
                <!--<div class="purchase-item">
                  <span class="purchase-left-con">起批量</span>
                  <span class="purchase-right-con">≥10件</span>
                   <span class="purchase-left-con weight-con">重量</span>
                  <span class="purchase-right-con">0.70kg</span>
                </div>-->
              </div>

              <div class="purchase-info-item" v-if="content.weight">
                <span class="purchase-left-con">重量</span>
                <span class="purchase-right-con">{{content.weight}}kg</span>
              </div>
              <!--<div class="purchase-info-item">
                <span class="purchase-left-con">快递</span>
                <span class="purchase-right-con">{{content.fareStyle == 'FREE'?'卖家承担运费': '买家承担运费'}}</span>
              </div>-->
              <div class="purchase-info-item">
                <span class="purchase-left-con size-con">规格</span>
                <span class="purchase-right-con specification-con">
                  <span :class="activeClass == i?'specification-list cursor active':'specification-list cursor'"
                        v-for="(item, i) in content.specifications" :key="i" @click="getIndex(i)">
                   <span v-if="item.value == null || item.value == ''">默认</span>
                   <span v-else>{{item.value}}</span>
                  </span>
                </span>
              </div>
              <div class="purchase-info-item">
                <span class="purchase-left-con">数量</span>
                <span class="purchase-right-con">
                  <el-input-number v-model="quantity" controls-position="right" :min="1"
                                   :max="inventory"></el-input-number>
                  <span class="inventory-num">库存{{inventory}}{{content.productUnit}}</span>
                </span>
              </div>
              <div class="purchase-button">
                <span class="purchase-comBtn buyNow-button" @click="buyNow">立即购买</span>
                <span class="purchase-comBtn add-cart" @click="addShoppingCart">加入进货车</span>
                <!-- <el-button type="primary" @click="buyNow">立即购买</el-button>
                <el-button type="primary" plain @click="addShoppingCart">加入进货车</el-button> -->
              </div>
            </div>

          </div>
          <div class="recommend-item fl">
            <div class="rec-title">大家都在看</div>
            <div class="rec-content" style="height: 412px;">
              <div class="recPD-list" v-for="(item,i) in seeList" :key="i">
                <nuxt-link :to="{name:'product-id',params: { id: item.productId }}">
                  <div class="recommend-pd">
                    <img :src="URL.PIC+item.productImage"/>
                    <div class="recommendPD-price">￥{{item.specification.sellingPrice}}</div>
                  </div>
                </nuxt-link>
              </div>
            </div>

            <div class="change-batch cursor" v-if="changeThree" @click="changeAllSee">换一批</div>
          </div>
        </div>

        <div class="product-detail-introduce-item">
          <div class="product-detail-left-lay fl">
            <!-- <div class="flagship-store-item">
              <div class="flagship-header">
                赛拓工具京东自营旗舰
                <img src="../../assets/images/product/detail/detail_08.png">
              </div>
              <div class="flagship-con">
                <div class="flagship-descript">
                  <div class="descript-list">
                    <div class="descript_title">描述</div>
                    <div class="descript_score arrow_in">
                      4.8
                      <img src="../../assets/images/product/detail/detail_09.png">
                    </div>
                  </div>
                  <div class="descript-list">
                    <div class="descript_title">服务</div>
                    <div class="descript_score warn_in">
                      4.8
                      <img src="../../assets/images/product/detail/detail_10.png">
                    </div>
                  </div>
                  <div class="descript-list">
                    <div class="descript_title">物流</div>
                    <div class="descript_score arrow_in">
                      4.8
                      <img src="../../assets/images/product/detail/detail_09.png">
                    </div>
                  </div>
                </div>
                <div class="flagship-button">
                  <el-button type="info">进店</el-button>
                  <el-button type="info" plain>收藏店铺</el-button>
                </div>
              </div>
            </div> -->
            <div class="hot-product-item">
              <div class="hot-product-header">热销商品排行</div>
              <div class="hot-product-con">
                <div class="hot-product-list" v-for="(item,index) in promotionList" :key="index">
                  <nuxt-link :to="{name:'product-id',params: { id: item.id }}">
                    <img :src="URL.PIC+item.mainImgPath">
                    <div class="hot-pd-price">￥{{item.sellingPrice}}</div>
                  </nuxt-link>
                </div>
              </div>
            </div>
          </div>
          <div class="product-detail-right-lay fl">
            <div class="product-detail-moreInfo">
              <div class="product-info-switchTab">
                <el-tabs v-model="activeName">
                  <el-tab-pane label="商品详情" name="first">
                    <!-- 商品详情的内容 -->
                    <div class="product-attribute">
                      <div class="product-attr-ul">
                        <div class="pd-attr-list" v-for="i in content.attributeValues">
                          <div class="pd-attr-left-con">{{i.productAttributeName}}：</div>
                          <div class="pd-attr-right-con">{{i.productAttributeValue}}</div>
                        </div>
                      </div>
                    </div>
                    <div class="product-info" v-html="content.details">
                    </div>
                    <!-- 商品详情的内容 -->
                  </el-tab-pane>
                  <el-tab-pane :label="'商品评价（'+total+'）'" name="second">
                    <div v-if="total > 0" class="product-comments">
                      <Comments ref="Comments" :id="id" @eventTotal="eventTotal"/>
                    </div>
                    <div v-else class="product-comments">
                      暂无评价
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
        </div>

        <LikeItem/>
      </div>
    </div>
    <Footbars/>
  </div>
</template>

<script>
  import ProductZoomer from './components/ProductZoomer'
  import Headbar from '@/components/Layouts/Headbar'
  import HeadMenu from '../factory/components/HeadMenu'
  import Hungbar from '@/components/Layouts/Hungbar'
  import NavList from '../factory/components/NavList'
  import BreadCrumb from './components/BreadCrumb'
  import Comments from './components/comments'
  import LikeItem from '@/components/Business/LikeItem'
  import Footbars from '@/components/Layouts/Footbars'
  // import vshare from 'vshare'
  import {getFactoryInfo, getFactoryClassify, getFactoryGoods} from '@/api/factory'

  import {
    productDetails,
    // getFactoryGoods,
    storeProductList,
    addShoppingCart,
    addFavorites,
    favoritesCount,
    addViewHistory,
    validateCart,
  } from '@/api/product'

  export default {
    name: 'PDdetail',
    components: {
      Headbar,
      Hungbar,
      HeadMenu,
      NavList,
      BreadCrumb,
      Comments,
      LikeItem,
      Footbars,
      // vshare
      ProductZoomer
    },
    data() {
      return {
        vshareConfig: {
          common : {
            bdText: null,
            bdUrl: null,
            bdPic: null,
          }
        },
        id: this.$route.params.id,
        // id: getUrlParams('id'),
        quantity: 1,
        active: 0,
        activeName: 'first',
        info: {},
        goodsClassify: null,
        content: {},
        factoryId: null,
        factoryName: null,
        list: null,
        contentFirstImg: null,
        defaultSpecification: '',
        promotionList: null,
        total: 0,
        inventory: 0,
        activeClass: 0,
        activeSpecificationId: null,
        salepPrice: null,
        productList: null,
        seePageNum: 0,
        seeList: [],
        favoritesCount: 0,
        activeShare: false,
        changeThree: true
      }
    },
    beforeRouteLeave(to, from, next) {
      // this.routeToPath(to.fullPath, 'current')

    },

    head () {
      return {
        title: '一呼百应工业品直卖网_'+this.info.factoryName+'_'+this.content.title+'',
        meta: [
          { name: 'keywords', content: '一呼百应,工业品直卖网,'+this.content.title+','+this.info.factoryName+','+this.content.categoryName+','+this.content.brand+',mro批发' }
        ]
      }
    },

    async asyncData ({ app, query }) {
      let products = await app.$axios.get('/product/select_product_details?productId='+app.context.params.id)
      let [res1, res2] = await Promise.all([
         app.$axios.get('/factory/frontend/factory/select_one?id='+products.data.data.factoryId),
         app.$axios.get('/product/front/classify/custom_list?factoryId='+products.data.data.factoryId),
       ])
       return {
         content: products.data.data,
         info: res1.data.data,
         goodsClassify: res2.data.data,
       }
    },

    created() {
      this.favoritesCounts();
      if (this.content.productStatus == "OBTAINED") {
        this.$alert('该商品已下架，请重新选择！', '提示', {
          confirmButtonText: '我知道了',
          callback: action => {
            this.routeToPath("/factory/" + this.content.factoryId)
          }
        });
      }
      this.factoryId = this.content.factoryId;
      this.factoryName = this.content.factoryName;
      this.getFactoryInfo(this.content.factoryId);
      this.getFactoryClassify(this.content.factoryId);
      this.getFactoryGoods(this.content.factoryId);
      this.getAllSeeList(this.content.factoryId);
      for (var idx in this.content.specifications) {
        if(this.content.specifications[idx].sellingPrice == this.content.defaultSpecification.sellingPrice){
          this.activeClass = idx;
          this.salepPrice = this.content.specifications[idx].sellingPrice;
          this.activeSpecificationId = this.content.specifications[idx].id;
          this.inventory = this.content.specifications[idx].inventory;
        }
      }
      this.contentFirstImg = this.content.images[0].imageURL;
    },
    methods: {
      // 获取云工厂信息
      getFactoryInfo(factoryId) {
        // getFactoryInfo({id: factoryId}).then(res => {
        //   this.info = res.data;
        // })
      },
      // 获取云工厂类目
      getFactoryClassify(factoryId) {
        // getFactoryClassify({factoryId: factoryId}).then(res => {
        //   this.goodsClassify = res.data;
        // })
      },
      eventTotal(val) {
        this.total = val;
      },
      //获取收藏统计数量
      favoritesCounts() {
        favoritesCount({favoriteId: this.id}).then(res => {
          this.favoritesCount = res.data.count;
        })
      },
      //获取大家都在看
      getAllSeeList(factoryId) {
        const params = {
          factoryId: factoryId,
          classifyId: null,
          size: 30,
          page: 1
        };
        storeProductList(params).then(res => {
          this.total = res.data.total;
          this.productList = res.data.list;
          if (this.productList && this.productList.length < 4) {
            this.changeThree = false;
          }
          this.changeAllSee();
        });
      },
      //换一批大家都在看
      changeAllSee() {
        this.seeList = [];
        if (this.seePageNum === this.productList.length) {
          this.seePageNum = 0;
        }
        for (var i = 0; i < 3 && this.seePageNum < this.productList.length; i++, this.seePageNum++) {
          this.seeList.push(this.productList[this.seePageNum])
        }
      },
      //热销排行
      getFactoryGoods(factoryId) {
        getFactoryGoods({
          size: 6,
          page: 1,
          factoryId: factoryId,
          salesVolumeSort: 'desc',
        }).then(res=>{
          console.log(res.data)
          console.log("res.data")
          this.promotionList = res.data.list;
        })
      },
      getIndex(index) {
        this.activeClass = index;
        this.salepPrice = this.content.specifications[index].sellingPrice;
        this.activeSpecificationId = this.content.specifications[index].id;
        this.inventory = this.content.specifications[index].inventory;
      },
      //点击图片
      changeImage(val, index) {
        this.contentFirstImg = val;
        this.active = index;
      },
      //立即购买
      buyNow() {

        if(!this.getUserInfo()){
          this.routeToPath('/login?redirect='+this.$router.history.current.fullPath)
          return
        }
        if (this.quantity == 0) {

        }
        this.getProductStatus();
        const params = {
          productSpecificationId: this.activeSpecificationId,
          quantity: this.quantity,
          factoryId: this.factoryId,
          factoryName: this.factoryName
        }
        validateCart(params).then(res => {
          if(res.code == 200){
            //console.log(this.$router)

            location.href = this.URL.mall+'/cart/confirmOrder?productSpecificationId='+this.activeSpecificationId+'&quantity='+this.quantity+''

            // this.$router.push({
            //   name: 'ConfirmOrder',
            //   query: {
            //     productSpecificationId: this.activeSpecificationId,
            //     quantity: this.quantity
            //   }
            // })
          }else{
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      },
      //商品收藏
      addFavorites() {
        this.getProductStatus();
        const params = {
          content: {
            image: this.content.images[0].imageURL,
            title: this.content.title,
            sellingPrice: this.salepPrice
          },
          favoriteId: this.id
        };
        addFavorites(params).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.msg
            });
            this.favoritesCount++;
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      },
      //加入购物车
      addShoppingCart() {
        if(!this.getUserInfo()){
          this.routeToPath('/login?redirect='+this.$router.history.current.fullPath)
          return
        }
        this.getProductStatus();
        const params = {
          productSpecificationId: this.activeSpecificationId,
          quantity: this.quantity,
          factoryId: this.factoryId,
          factoryName: this.factoryName
        };

        addShoppingCart(params).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.msg
            });
            this.$refs.Hungbar.getUserCartNum();
          } else if (res.code == '20011027') {
            this.$alert('进货车商品超过100件，请先删除！', '提示', {
              confirmButtonText: '我知道了'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      },
      //查询商品是否已下架或删除
      getProductStatus() {
        productDetails(this.id).then(res => {
          if (res.data && res.data.productStatus == "OBTAINED") {
            this.$alert('该商品已下架，请重新选择！', '标题名称', {
              confirmButtonText: '我知道了',
              callback: action => {
                this.routeToPath("/factory?factoryId=" + this.content.factoryId)
              }
            });
          }
        });
      },
      shareProduct() {
        this.activeShare=!this.activeShare;
        this.vshareConfig.common.bdText = this.content.title;
        this.vshareConfig.common.bdPic = this.URL.PIC + this.content.images[0].imageURL;
        this.vshareConfig.common.bdUrl = window.location.href;
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/pages/product.scss';
  .product-attribute{
    font-size: 14px;
    color: #888;
    .product-title{

      .pd-attr-left-con{
        display: inline-block;
        margin-left: 20px;
      }
      .pd-attr-right-con{
        display: inline-block;
      }
    }
    .product-attr-ul{
      .pd-attr-list{
        width: 33%;
        margin: 10px 0;
        display: inline-block;

        .pd-attr-left-con{
          display: inline-block;
          margin-left: 20px;
          vertical-align: middle;
        }
        .pd-attr-right-con{
          display: inline-block;
          max-width: 210px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          vertical-align: middle;
        }
      }
    }
  }
</style>
<style lang="scss">
  .product-container {
    .el-input-number {
      width: 105px;
      line-height: 32px;
    }

    .el-input__inner {
      height: 36px;
      line-height: 36px;
      border-radius: 0;
      border: 1px solid #BEBEBE;
    }

    .el-input-number.is-controls-right .el-input-number__decrease,
    .el-input-number.is-controls-right .el-input-number__increase {
      line-height: 16px;
    }

    .flagship-button {
      .el-button {
        padding: 0;
        width: 68px;
        height: 30px;
        font-size: 12px;
        border-radius: 0;
      }
    }

    .product-detail-moreInfo {
      .el-tabs__nav {
        padding-left: 20px;
      }
      .el-tabs__nav-scroll {
        border: 1px solid #E3DFDF;
      }
      .el-tabs__active-bar {
        left: 20px;
      }

    }
  }

</style>
